﻿using NineSeas.Models;
using NineSeas.Services;
using Orchard;
using Orchard.ContentManagement;
using Orchard.ContentManagement.Handlers;
using Orchard.Data;

namespace NineSeas.Handlers
{
    public class BookPartHandler: ContentHandler
    {
        public BookPartHandler(IRepository<BookPartRecord> repository,
            IChapterService chapterService,
            IOrchardServices services)
        {
            Filters.Add(StorageFilter.For(repository));

            OnPublished<BookPart>((context, part) => {
                var chapters = services.ContentManager.Query<ChapterPart, ChapterPartRecord>()
                        .ForVersion(VersionOptions.Latest)
                        .Where(c => c.BookId == part.Id)
                        .List();

                foreach (var chapter in chapters)
                {
                    if (!chapter.ContentItem.VersionRecord.Published)
                    {
                        services.ContentManager.Publish(chapter.ContentItem);
                    }
                }
            });
        }
    }
}